import request, { requestOld } from '@/utils/request'
import { batchTask } from '../deviceMonitor/work'
import { Message } from 'element-ui'

// 查询时段参数列表
export function tpList(query) {
  return request({
    url: '/param/tp/list',
    method: 'get',
    params: query
  })
}

// 召测时段参数
export function tpCall(query) {
  return batchTask({
    newUrl: '/param/tp/call',
    oldUrl: '/ChaobiaoModule/Tparam_tp/GetCheckData',
    meterNos: query.meterNos,
    rooms: query.rooms,
    updateUrl: '/old/refresh/param/tp',
    onItemOver: query.onItemOver
  })
}

// 设置时段参数
export async function tpSet(data, onItemOver) {
  const oldItems = []
  const newItems = []
  data.tparamTpList.forEach((item, i) => {
    // 设备编号/电表号大于255的是老系统电表，调老接口
    if (Number(item.meterNo) > 255) {
      oldItems.push(data.tparamTpList[i])
    } else {
      newItems.push(data.tparamTpList[i])
    }
  })
  const tasks = []
  // 新系统接口
  for (const item of newItems) {
    tasks.push(() => request({
      url: '/param/tp/set',
      method: 'post',
      data: [item]
    }).then(res => {
      return {
        ...item,
        roomId: item.roomId,
        status: res.data.statusList?.[0]?.status + '' || '1'
      }
    }))
  }
  if (oldItems.length > 0) {
    // 旧系统接口，旧系统接口只支持一个一个改，要调用多次接口
    tasks.push(...oldItems.map(oldRoom => {
      const data = new FormData()
      data.append("Room", oldRoom.roomId)
      oldRoom.Send1 = oldRoom.isBatch == 1 ? 'on' : 'off'
      oldRoom.Batch1 = oldRoom.isBatch == 1 ? 'on' : 'off'
      data.append("DetailList", JSON.stringify([oldRoom]))
      return () => requestOld({
        url: '/ChaobiaoModule/Tparam_tp/SubmitParam?RoomId=' + oldRoom.roomId + '&LoopNo=1',
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data
      }).then(res => {
        return {
          ...oldRoom,
          status: res.status,
          roomId: oldRoom.roomId
        }
      }, err => {
        return {
          ...oldRoom,
          status: '1',
          roomId: oldRoom.roomId
        }
      })
    }))
  }
  async function nextTask() {
    const task = tasks.shift()
    if (!task) {
      return
    }
    const res = await task()
    onItemOver?.(res)
    await nextTask()
  }
  await nextTask()
  if (oldItems.length > 0) {
    await request({
      url: '/old/refresh/param/tp',
      method: 'get',
      params: {
        roomIds: oldItems.map(item => item.roomId).toString()
      }
    }).catch(err => {
      Message.error('同步失败')
    })
  }
}